package com.my.xq.repository;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import com.my.xq.domain.ProprietorQueryParam;
import com.my.xq.domain.entity.Proprietor;
import com.sskj.core.query.annotation.DynamicQuery;
import com.sskj.core.repository.GenericRepository;

public interface ProprietorRepository extends GenericRepository<Proprietor, String> {
	@DynamicQuery
	Page<Proprietor> findPage(ProprietorQueryParam pqp, Pageable pageable);

	@Query(value = " from Proprietor x where 1=1 " + "<notEmpty name='name'> and x.name like '%${name}%' </notEmpty> "
			+ "<notEmpty name='phone'> and x.phone like '%${phone}%' </notEmpty> " + " and x.priType='业主' "
			+ " order by  x.createdTime asc")
	@DynamicQuery
	Page<Proprietor> findYeZuPage(ProprietorQueryParam queryParam, Pageable pageable);

	@Query(value = "from Proprietor o where o.name=?1")
	Proprietor findOneByName(String name);

	@Query("from  Proprietor  x  where x.identityCard = ?1")
	Proprietor findByCert(String cert);

	@Query("SELECT r FROM Proprietor r where r.identityCard = ?1")
	Proprietor findPropriByCard(String card);

	@Query("SELECT r FROM Proprietor r where r.phone = ?1")
	List<Proprietor> findPropriByPhone(String phone);

	@Query(value = " from Proprietor x where 1=1 " + "<notEmpty name='name'> and x.name like '%${name}%' </notEmpty> "
			+ " order by  x.createdTime asc")
	@DynamicQuery
	Page<Proprietor> findManyByName(ProprietorQueryParam queryParam, Pageable pageable);

	@Transactional
	@Modifying(clearAutomatically = true)
	@Query("UPDATE Proprietor SET openid = ?1" + " where id = ?2")
	void wenxinbindProprietor(String openId, String proprietorId);

	@Query(value = "from Proprietor o where o.openid=?1")
	Proprietor findProprietorByOpenId(String openId);

	@Query(value = "select p.phone as phone from Proprietor p where p.identityCard=?1")
	String getPhoneByCertNum(String identityCard);

	@Transactional
	@Modifying(clearAutomatically = true)
	@Query(value = "update Proprietor t set t.record = ?2, t.synopsis = ?3, t.imageUrl =?4 where t.id = ?1")
	void updIntro(String proprietorId, String record, String synopsis, String imgUrl);

	@Query(value = "SELECT P FROM Proprietor P WHERE P.id = (select D.proprietorId from Doorplate D where D.id = ?1)")
	Proprietor findProprietorByDoorId(String doorId);
}
